package com.xiaoxin.smartbi.bizmq;

import com.rabbitmq.client.Channel;
import com.xiaoxin.smartbi.common.ErrorCode;
import com.xiaoxin.smartbi.exception.BusinessException;
import com.xiaoxin.smartbi.manager.AiManager;
import com.xiaoxin.smartbi.model.entity.Chart;
import com.xiaoxin.smartbi.service.ChartService;
import com.xiaoxin.smartbi.utils.ExcelUtils;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
@Slf4j
public class BiMessageConsumer {
    @Resource
    private AiManager aiManager;

    @Resource
    private ChartService chartService;

    @SneakyThrows
    @RabbitListener(queues = {"bi_copy_queue"},ackMode = "MANUAL")
    public void receiveMessage(String message, Channel channel,@Header(AmqpHeaders.DELIVERY_TAG) long deliverTag){
        if(message==null){
            channel.basicNack(deliverTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"消息接收失败");
        }
        Chart chart=chartService.getById(Long.parseLong(message));
        String excelToCsv = chart.getChartData();
        String goal = chart.getGoal();
        String chartType = chart.getChartType();
        StringBuilder input=new StringBuilder();
        input.append("分析需求：\n"+goal+"，请使用"+chartType).append("\n");
        input.append("原始数据：\n"+excelToCsv);

        String result = aiManager.result(input.toString());
        //状态2，ai生成中
        Chart chart2=new Chart();
        chart2.setId(chart.getId());
        chart2.setStatus("running");
        String[] resultArray= result.split("【【【【");
        chart2.setGenChart(resultArray[1]);
        chart2.setGenResult(resultArray[2]);
        boolean update = chartService.updateById(chart2);
        if(!update){
            //状态3，ai生成失败
            Chart chart3=new Chart();
            chart3.setId(chart.getId());
            chart3.setStatus("filed");
            boolean update2 = chartService.updateById(chart3);
            if(!update2){
                channel.basicNack(deliverTag,false,false);
                throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表信息保存失败");
            }
            channel.basicNack(deliverTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"ai生成图表失败");
        }
        Chart chart4=new Chart();
        chart4.setId(chart.getId());
        chart4.setStatus("succeed");
        boolean update4 = chartService.updateById(chart4);
        if(!update4){
            channel.basicNack(deliverTag,false,false);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"图表信息保存失败");
        }
        channel.basicAck(deliverTag,false);
    }
}
